package cn.edu.scnu.report.controller;

import cn.edu.scnu.report.entity.MovieReport;
import cn.edu.scnu.report.service.ReportService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/api")
@RestController
public class ReportController {

    @Autowired
    private ReportService reportService;

    @GetMapping("/download/report")
    public void downloadMovieReport(HttpServletResponse response) {
        Workbook workbook;
        try {
            workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("电影播放排行");

            // 表头样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setBold(true);
            headerStyle.setFont(font);

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"排名", "电影名称", "类型", "播放量", "导演"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 查询数据
            List<MovieReport> reports = reportService.getMovieData();

            // 填充数据
            int rowNum = 1;
            for (MovieReport report : reports) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(report.getRank());
                row.createCell(1).setCellValue(report.getTitle());
                row.createCell(2).setCellValue(report.getType());
                row.createCell(3).setCellValue(report.getTotalHits());
                row.createCell(4).setCellValue(report.getDirector());
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

        } catch (Exception e) {
            throw new RuntimeException("创建Excel失败", e);
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=Movie_Playlist_Report.xlsx");

        // 写出到响应流（自动关闭）
        try (ServletOutputStream out = response.getOutputStream()) {
            workbook.write(out); // 写出内容
        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        } finally {
            try {
                workbook.close(); // 最后关闭
            } catch (IOException e) {
                // 忽略关闭异常
            }
        }
    }

    @GetMapping("/report/movies/data")
    public Map<String,Object> getMoviedata(){
        List<MovieReport> reports = reportService.getMovieData();
        List<String> titles = reports.stream().map(MovieReport::getTitle).toList();
        List<Integer> hits = reports.stream().map(MovieReport::getTotalHits).toList();

        Map<String, Object> result = new HashMap<>();
        result.put("titles", titles);
        result.put("hits", hits);
        return result;
    }
}
